<template>

  <div>
    <div style="width: 80%; margin-right: 10%; margin-left: 10%;">
      <el-select v-model="rouletteDataStore.rouletteData" placeholder="请选择" @change="initLogList">
        <el-option
            v-for="item in rouletteDataStore.rouletteDataList"
            :key="item"
            :label="item"
            :value="item"
        />
      </el-select>
      <div style="float: right">
        <el-input v-model="rouletteDataInput" style="width: auto" placeholder="自定义数据源名称" />
        <el-button @click="submitRouletteDataInput()">创建数据源</el-button>
      </div>
    </div>

    <el-card v-if="rouletteDataStore.rouletteData == null || rouletteDataStore.rouletteData === ''" style="width: 80%; margin-right: 10%; margin-left: 10%;">
      <el-empty description="暂无数据,可以通过下方或右上角的创建数据源或在左上角选择数据源开始记录你的导随(要导入数据得先创建一个空的数据源)">
        <div>
          <el-input v-model="rouletteDataInput" style="width: auto" placeholder="自定义数据源名称" />
          <el-button @click="submitRouletteDataInput()">创建数据源</el-button>
        </div>
      </el-empty>
    </el-card>

    <el-card v-if="rouletteDataStore.rouletteData != null && rouletteDataStore.rouletteData !== ''" class="logListCard-container">

      <div slot="header" class="clearfix">
        <span style="font-size: x-large"><i class="el-icon-s-management" />{{ rouletteDataStore.rouletteData }}</span>
        <span style="margin-left: 10px">-已导{{logListStore.index}}把</span>

        <el-button style="float: right;margin-left: 10px" type="danger" plain @click="deleteRouletteData">销毁当前数据源</el-button>
        <el-button style="float: right;margin-left: 10px" @click="dialog_import_visible = true">导入</el-button>
        <el-dropdown style="float: right;margin-left: 10px">
          <el-button>导出</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="exportExcel">导出为excel表格</el-dropdown-item>
              <el-dropdown-item @click="exportJSON">导出为json数据</el-dropdown-item>
              <el-dropdown-item @click="logListStore.save2Gitee" v-if="accountStore.getGitee().access_token !== ''">上传至gitee</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button style="float: right;margin-left: 10px" @click="logListStore.sort">自动排序</el-button>

      </div>

      <el-divider />

      <el-button style="width: 100%" type="primary" @click="dialog_add_visible = true">
        <el-icon><Plus /></el-icon>
      </el-button>

      <el-divider />

      <el-pagination
          v-model:current-page="page.currentPage"
          :page-size="page.size"
          layout="prev, pager, next"
          :total="logListStore.getLength()"
          background
      />

      <el-table
          :data="logList"
          stripe
      >

        <el-table-column
            prop="count"
            label="完成场次"
            sortable
            width="120"
        />

        <el-table-column
            prop="duty"
            label="副本"
            width="280"
        >
          <template #default="scope">
            <Duty :value="scope.row.duty"/>
          </template>
        </el-table-column>
        <el-table-column
            prop="job"
            label="职业"
            width="100"
        >
          <template #default="scope">
            <Job :value="scope.row.job"/>
          </template>
        </el-table-column>
        <el-table-column
            prop="completed"
            label="完成情况"
            width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.completed" style="margin-left: 10px">完成</span>
            <span v-if="!scope.row.completed" style="margin-left: 10px">未完成</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="description"
            label="描述"
        >
          <template #default="scope">
            <span style="margin-left: 10px">{{subDescription(scope.row.description)}}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="date"
            label="日期"
            sortable
            width="200"
            :formatter="timeFormatter"
        />
        <el-table-column width="200">
          <template #default="scope">
            <el-button @click="updateButton(scope)">详情</el-button>
            <el-popconfirm
                @confirm="deleteButton(scope)"
                title="确定删除该条记录吗"
            >
              <template #reference>
                <el-button slot="reference">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>

    </el-card>

    <el-dialog
        title="添加导随记录"
        v-model="dialog_add_visible"
        width="50%"
    >
      <el-form label-position="right" label-width="80px" :model="logInput.addLog">
        <el-form-item label="完成场次">
          <el-input v-model="logInput.addLog.count"/>
        </el-form-item>
        <el-form-item label="副本名">
          <DutyAutoComplete v-model="logInput.addLog.duty"/>
        </el-form-item>

        <el-form-item label="职业">
          <JobSelector v-model="logInput.addLog.job" />
        </el-form-item>
        <el-form-item label="是否完成">
          <el-switch v-model="logInput.addLog.completed" @change="onCompleteButtonChange" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="logInput.addLog.description" type="textarea" />
        </el-form-item>
        <el-form-item label="图片链接">
          <el-input v-model="logInput.addLog.image"></el-input>
          <img v-if="logInput.addLog.image !== '' && logInput.addLog.image != null" :src='logInput.addLog.image' alt='无法显示链接图片,请检查链接或联系开发人员'/>
          <a v-else href='https://postimages.org/' target='_blank'>打开建议的图床网站上传图片</a>
        </el-form-item>
        <el-form-item label="时间">
          <div class="block">
            <el-date-picker
                v-model="logInput.addLog.date"
                type="datetime"
                placeholder="选择日期时间"
                :shortcuts="getPickerOptions().shortcuts"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="dialog_add_visible = false">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog
        title="修改导随记录"
        v-model="dialog_update_visible"
        width="50%"
    >
      <el-form label-position="right" label-width="80px" :model="logInput.updateLog">
        <el-form-item label="完成场次">
          <el-input v-model="logInput.updateLog.count"/>
        </el-form-item>
        <el-form-item label="副本名">
          <DutyAutoComplete v-model="logInput.updateLog.duty"/>
        </el-form-item>

        <el-form-item label="职业">
          <JobSelector v-model="logInput.updateLog.job" />
        </el-form-item>
        <el-form-item label="是否完成">
          <el-switch v-model="logInput.updateLog.completed" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="logInput.updateLog.description" type="textarea" />
        </el-form-item>
        <el-form-item label="图片链接">
          <el-input v-model="logInput.updateLog.image"></el-input>
          <img v-if="logInput.updateLog.image !== '' && logInput.updateLog.image != null" :src='logInput.updateLog.image' alt='无法显示链接图片,请检查链接或联系开发人员'/>
          <a v-else href='https://postimages.org/' target='_blank'>打开建议的图床网站上传图片</a>
        </el-form-item>
        <el-form-item label="时间">
          <div class="block">
            <el-date-picker
                v-model="logInput.updateLog.date"
                type="datetime"
                placeholder="选择日期时间"
                :shortcuts="getPickerOptions().shortcuts"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onUpdate">修改</el-button>
          <el-button @click="dialog_update_visible = false">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog
        title="导入"
        v-model="dialog_import_visible"
        width="50%"
    >
      <ul class="lineH-right" style="line-height: 1.7">
        <li><span>可以导入表格(.xls .xlsx)或者从本站导出的json数据(.json)</span></li>
        <li><span>导入excel表格的话请使用从本站导出的excel或者下载示例模板后填入自己的数据导入,可以省去很多不必要的麻烦</span><br/><el-button link type="primary" @click="downloadExampleExcel">（点我获取示例模板）</el-button></li>
        <span>ps：示例模板会有输入限制引导，导出的表格是没有的</span>
      </ul>
      <el-upload
          v-loading="uploadLoading"
          action=""
          class="upload-demo"
          ref="upload"
          drag
          accept=".json,.xlsx,.xls"
          :on-change="importData"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed">
        <div>点击或拖拽上传</div>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { useRouletteDataStore } from "@/data/stores/rouletteData";
import { useLogListStore } from '@/data/stores/logList'
import { useSettingsStore } from '@/data/stores/settings';
import { useAccountStore } from "@/data/stores/account";
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { SampleData, SUFFIX_JSON, SUFFIX_XLSX, SUFFIX_XLS } from '@/data/constants/Constants'
import { getPickerOptions, parseTime } from "@/utils/timeUtils";
import { Plus, UploadFilled } from '@element-plus/icons-vue';
import type { Log } from "@/data/entity/Log";
import { formatLogListFromExcel, formatLogListToExcel } from "@/data/service/logFormatService";
import { Object2Blob } from "@/utils";
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { genFileId } from 'element-plus'
import JobSelector from '@/views/components/JobSelector/index.vue'
import Job from '@/views/components/Job/index.vue'
import Duty from '@/views/components/Duty/index.vue'
import DutyAutoComplete from '@/views/components/DutyAutoComplete/index.vue'
import FileSaver from 'file-saver'
import * as XlsxUtils from '@/utils/xlsxUtils'


const rouletteDataStore = useRouletteDataStore()
const logListStore = useLogListStore()
const settingStore = useSettingsStore()
const accountStore = useAccountStore()

const rouletteDataInput = ref('')
const dialog_add_visible = ref(false)
const dialog_update_visible = ref(false)
const dialog_import_visible = ref(false)
const logInput = reactive({
  addLog: <Log>{},
  oldLog: <Log>{},
  updateLog: <Log>{}
})
const page = reactive({
  currentPage: 1,
  size: 30,
})
const upload = ref<UploadInstance>()
const uploadLoading = ref(false)

onMounted(()=>{
  initLog()
  initLogList()
})

const logList = computed(()=>{
  return logListStore.getReverseLogList((page.currentPage - 1)*page.size ,page.size)
})

function submitRouletteDataInput(){
  let createdRouletteData =  rouletteDataStore.addRouletteData(rouletteDataInput.value)
  if (createdRouletteData){
    rouletteDataStore.rouletteData = createdRouletteData
  }
  logListStore.reset()
}
function initLogList(){
  logListStore.reset()
}
function deleteRouletteData(){
  ElMessageBox.confirm(
      '确定要销毁本数据源吗？销毁后就连缓存都会清除，清慎重考虑！建议销毁前先导出为excel或json作为备份！',
      '销毁' + rouletteDataStore.rouletteData,
      {
        confirmButtonText: '我已备份，确定要销毁这个叫\'' + rouletteDataStore.rouletteData +'\'的数据源',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
  .then(() => {
    logListStore.delLogList(rouletteDataStore.rouletteData)
    rouletteDataStore.delRouletteData(rouletteDataStore.rouletteData)
    logListStore.reset()
    ElMessage({
      type: 'success',
      message: '已删除',
    })
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}
function timeFormatter(row:any){
  return parseTime(new Date(row.date).getTime(), '')
}
function deleteButton(scope:any){
  logListStore.deleteLog(scope.row)
  ElMessage({
    type: 'info',
    message: '已删除'
  });
}
function updateButton(scope:any){
  logInput.oldLog = scope.row
  logInput.updateLog = JSON.parse(JSON.stringify(scope.row))
  dialog_update_visible.value = true
}
function subDescription(str:string){
  if (str.length > 15){
    return str.substring(0, 30) + '...'
  }
  return str
}

function onSubmit() {
  const log = JSON.parse(JSON.stringify(logInput.addLog))
  logListStore.addLog(log)
  dialog_add_visible.value = false
  initLog()
  ElMessage({
    message: '记录成功',
    type: 'success'
  });
}
function onUpdate() {
  logListStore.updateLog(logInput.oldLog, JSON.parse(JSON.stringify(logInput.updateLog)))
  dialog_update_visible.value = false
  ElMessage({
    message: '更新成功',
    type: 'success'
  });
}
function onCompleteButtonChange(b:any){
  logInput.addLog.count = b ? logListStore.index + 1 : -1
}
function initLog() {
  logInput.addLog = JSON.parse(JSON.stringify(settingStore.defaultLog))
  logInput.addLog.count = logInput.addLog.completed ? logListStore.index + 1 : -1
}
function downloadExampleExcel(){
  const href = new URL('@/assets/example/example.xlsx', import.meta.url).href;
  FileSaver.saveAs(href, "example.xlsx")
}
// 导出json
function exportJSON() {
  // 将json转换成字符串
  const blob = Object2Blob(logListStore.logList, '')
  FileSaver.saveAs(blob, rouletteDataStore.rouletteData + SUFFIX_JSON)
}

// 导入json
function importJSONFile(file:any) {
  const reader = new FileReader()
  reader.readAsText(file.raw)
  reader.onload = function() {
    // this.result为读取到的json字符串，需转成json对象
    logListStore.addLogList(JSON.parse(<string>this.result).data)
    uploadLoading.value = false
  }
}
function importExcel(file:any) {
  XlsxUtils.importExcel(file.raw).then((rs:any) => {
    let logList = formatLogListFromExcel(rs)
    logListStore.addLogList(logList)
    uploadLoading.value = false
  })
}

function importData(file:File){
  uploadLoading.value = true
  const suffix = file.name.substring(file.name.lastIndexOf('.'))
  switch (suffix) {
    case SUFFIX_XLSX:
    case SUFFIX_XLS:
      importExcel(file)
      break
    case SUFFIX_JSON:
      importJSONFile(file)
      break
    default:
      ElMessage({
        message: '不支持的文件类型',
        type: 'warning'
      });
  }
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

function exportExcel(){
  let formattedLogList = formatLogListToExcel(logListStore.getLogList(0, logListStore.getLength()))
  XlsxUtils.exportExcel(rouletteDataStore.rouletteData + SUFFIX_XLSX, formattedLogList)
}
</script>



<style scoped>
.logListCard-container{
  width: 80%;
  margin-right: 10%;
  margin-left: 10%;
}
</style>
